package crudfx.field;
import javafx.scene.*;
import javafx.scene.paint.*;
import javafx.scene.shape.*;
import javafx.ext.swing.*;
import javax.swing.*;
import crudfx.interop.*;
import crudfx.data.*;
import java.util.*;
//import crudfx.properties.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
/**
 * @profile desktop
 * @author Sergey Surikov
 */

public class ListField extends UIComponent{
    protected var jComboBox:JComboBox;
    var model:DefaultComboBoxModel;
    var lock=true;
    //public var choosen:Fields on replace {validateText(); };
    public var row:Integer=0 on replace {setValue();};
    public var key:String="";
    public var title:String="";
    function setValue():Void{
        if(lock)return;
        jComboBox.setSelectedIndex(row);
        }
    /*function validateText():Void{
        if(lock)return;
        var n:Integer=0;
        for(s:Fields in values){
            if(s.get(key).equals(choosen)){
                jComboBox.setSelectedIndex(n);
                return;
                }
            n=n+1;
            }
        jComboBox.setSelectedIndex(0);
        choosen=values[0];
        //jComboBox.getItemAt(0).toString();
        }*/
    public var values:Fields[] on replace {fill();};
    function fill(){
        lock=true;
        model.removeAllElements();
        for(s:Fields in values){
            model.addElement(s.get(title));
            //println(s.get(title));
            //println(s);
            }
        jComboBox.setSelectedIndex(row);
        lock=false;
        //validateText();
        }
    init{
        jComboBox=new JComboBox();
        jComboBox.setEditable(false);
        model=jComboBox.getModel() as DefaultComboBoxModel;
        fill();
        var listener=ItemListener{
            override function itemStateChanged(e:ItemEvent):Void{
                lock=true;
                //text=jComboBox.getItemAt(jComboBox.getSelectedIndex()).toString();
                //choosen=values[jComboBox.getSelectedIndex()];
                row=jComboBox.getSelectedIndex();
                lock=false;
                }
            };
        jComboBox.addItemListener(listener);
        }
    override public function getJComponent():JComponent{
        return jComboBox;
        }
    override public function highlight(s:String):Boolean{
        return false;
        }
    override public function gather():DataTree{
        var me:DataTree=DataTree{ name:"ListField" };
        //me.node("text").asString("").value=text;
        return me;
        }
    }
